//
//  AppDelegate.m
//  跨界收
//
//  Created by MT on 2018/10/26.
//  Copyright © 2018年 gztx. All rights reserved.
//

#import "AppDelegate.h"
#import <AVFoundation/AVFoundation.h>
#import <IQKeyboardManager.h>
#import "LoginViewController.h"
#import "TabBarController.h"

static NSString *channel = @"Publish channel";

@interface AppDelegate ()

@property(nonatomic,assign)int setAliasCount;

@property(nonatomic,copy)NSString *alias;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    // 注册 APNs
    [self registerRemoteNotification];
    //极光推送设置
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                          UIUserNotificationTypeSound |
                                                          UIUserNotificationTypeAlert)
                                              categories:nil];
    } else {
        //categories 必须为nil
        [JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                          UIRemoteNotificationTypeSound |
                                                          UIRemoteNotificationTypeAlert)
                                              categories:nil];
    }
    
    
    //企业证书推送appKey:38aec9ce52ec1e05a2ceb191    包名:com.ios.kuajieshou    tagrget包名:com.ios.kuajieshou.pushTarget
    //上架证书推送appkey:d9d4d6afe1a178d019cffffe    包名:com.gztx.kuajieshou   tagrget包名:com.gztx.kuajieshou.pushTarget
    [JPUSHService setupWithOption:launchOptions appKey:@"38aec9ce52ec1e05a2ceb191" channel:channel apsForProduction:YES advertisingIdentifier:nil];
    
    
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    
    
    [self setAppearance];
    
    [self setupServerURL];
    
    //创建根视图
    [self setupRootViewController];
    
    NSError *error = NULL;
    
    AVAudioSession *session = [AVAudioSession sharedInstance];
    
    [session setCategory:AVAudioSessionCategoryPlayback error:&error];
    
    if(error) {
        // Do some error handling
        
    }
    
    [session setActive:YES error:&error];
    
    if (error) {
        // Do some error handling
    }
    
    // 让app支持接受远程控制事件
    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
    if (launchOptions) {
        NSDictionary * remoteNotification = [launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
        //这个判断是在程序没有运行的情况下收到通知，点击通知跳转页面
        if (remoteNotification) {
            
        }
    }
    
    return YES;
}

//创建根视图
- (void)setupRootViewController
{
    if ([Tool isLogined]) {
        TabBarController *controller = [[TabBarController alloc]init];
        controller.selectedIndex = 1;
        self.window.rootViewController = controller;
    } else {
        LoginViewController *controller = [[LoginViewController alloc] initWithNibName:@"LoginViewController" bundle:nil];
        UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:controller];
        self.window.rootViewController = navi;
     }
    DebugLog(@"user = %@", [UserModel sharedModel].description);
}

/// 设置全局导航栏皮肤
- (void)setAppearance {
    UINavigationBar *nb = [UINavigationBar appearance];
    nb.tintColor = [UIColor whiteColor];
    [nb setBackgroundImage:[UIImage imageWithColor:[UIColor cz_colorWithHex:0x219fdb]] forBarMetrics:UIBarMetricsDefault];
    nb.backIndicatorImage = [UIImage imageNamed:@"nav_white"];
    nb.backIndicatorTransitionMaskImage = [UIImage imageNamed:@"nav_white"];
    // 去掉分割线
    nb.shadowImage = [[UIImage alloc] init];
    
    NSDictionary * attr = @{NSFontAttributeName:[UIFont systemFontOfSize:17],NSForegroundColorAttributeName:[UIColor whiteColor],};
    nb.titleTextAttributes = attr;

    UIBarButtonItem *bbi = [UIBarButtonItem appearance];
    [bbi setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor whiteColor],} forState:UIControlStateNormal];
    [bbi setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:14],NSForegroundColorAttributeName:[UIColor whiteColor],} forState:UIControlStateHighlighted];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

/** 注册 APNs */
- (void)registerRemoteNotification {
    /*
     警告：Xcode8 需要手动开启"TARGETS -> Capabilities -> Push Notifications"
     */
    
    /*
     警告：该方法需要开发者自定义，以下代码根据 APP 支持的 iOS 系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的 iOS 系统都能获取到 DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
                NSLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    
    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidLoginNotification object:nil];
    
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // 向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
    
    //注销通知
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kJPFNetworkDidLoginNotification object:nil];
}

- (void)aliasCallBack:(int)iscall tag:(NSSet*)tags andAlias:(NSString*)alias
{
    NSLog(@"iscode%d--alias=%@--tags=%@",iscall,alias,tags);
    
    if (iscall != 0 && self.setAliasCount <= 3) {
        [JPUSHService setAlias:self.alias callbackSelector:@selector(aliasCallBack:tag:andAlias:) object:self];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [JPUSHService handleRemoteNotification:userInfo];
    
    // 将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
    
    if ([[UIDevice currentDevice].systemVersion floatValue] < 10.0) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:userInfo];
        NSString *str;
        if ([[dic allKeys] containsObject:@"voice"]) {
            str = dic[@"voice"];
        }else{
            str = dic[@"aps"][@"alert"][@"body"];
        }
        AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:str];
        
        AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
        
        [synth speakUtterance:utterance];
    }
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    // apn 内容获取：
    // 取得 APNs 标准信息内容
    [JPUSHService handleRemoteNotification:userInfo];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    [JPUSHService setBadge:0];
    [[UIApplication sharedApplication] cancelAllLocalNotifications];
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0

//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发，在该方法内统计有效用户点击数
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    NSLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    completionHandler();
}

#endif

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

- (void)GeTuiSdkDidAliasAction:(NSString *)action result:(BOOL)isSuccess sequenceNum:(NSString *)aSn error:(NSError *)aError {
    if ([kGtResponseBindType isEqualToString:action]) {
        NSLog(@"绑定结果 ：%@ !, sn : %@", isSuccess ? @"成功" : @"失败", aSn);
        if (!isSuccess) {
            NSLog(@"失败原因: %@", aError);
        }
    } else if ([kGtResponseUnBindType isEqualToString:action]) {
        NSLog(@"绑定结果 ：%@ !, sn : %@", isSuccess ? @"成功" : @"失败", aSn);
        if (!isSuccess) {
            NSLog(@"失败原因: %@", aError);
        }
    }
}

/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    //收到个推消息
    NSString *payloadMsg = nil;
    NSString *voiceStr = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
        NSError *error;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:payloadData options:NSJSONReadingMutableContainers error:&error];
        voiceStr = dic[@"voice"];
    }
    
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@",taskId,msgId, payloadMsg,offLine ? @"<离线消息>" : @""];
    NSLog(@"\n>>>[GexinSdk ReceivePayload]:%@\n\n", msg);
    
    AVSpeechUtterance *utterance = [AVSpeechUtterance speechUtteranceWithString:voiceStr];
    
    AVSpeechSynthesizer *synth = [[AVSpeechSynthesizer alloc] init];
    
    [synth speakUtterance:utterance];
}

#pragma mark - Private
/** 获取服务器地址 */
- (void)setupServerURL
{
    [NetworkManager post:nil parameters:nil success:^(id data) {
        [Tool setLocalDataValue:data[@"domain"] key:kServerURLKey];
    } failure:^(NSError *error) {
        
    }];
}

- (void)bindApnsAlias
{
    NSString *alias = [UserModel sharedModel].jg_alias;
    NSParameterAssert(alias.length > 0);
    [JPUSHService setAlias:alias callbackSelector:@selector(aliasCallBack:tag:andAlias:) object:self];
    [GeTuiSdk bindAlias:alias andSequenceNum:kGtAppName];
}

#pragma mark - Public
+ (AppDelegate *)sharedDelegate
{
    return (AppDelegate *)[UIApplication sharedApplication].delegate;
}

- (void)doLogin
{
    [self bindApnsAlias];
    [self setupRootViewController];
}

- (void)doLogout
{
    [USER_DEFAULT removeObjectForKey:kAccessTokenKey];
    [[UserModel sharedModel] deleteFromDisk];
    [self setupRootViewController];
}

@end
